﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BFlatCompile.Nodes
{
	public class Switch : Executable
	{
		public Expression Condition { get; private set; }
		public SwitchCase[] Cases { get; private set; }

		private Switch(Expression condition, SwitchCase[] cases)
		{
			this.Condition = condition;
			this.Cases = cases;
		}

		public static Executable Parse(Tokens tokens)
		{
			tokens.PopExpected("switch");
			tokens.PopExpected("(");
			Expression condition = Expression.Parse(tokens);
			tokens.PopExpected(")");
			tokens.PopExpected("{");

			List<SwitchCase> cases = new List<SwitchCase>();

			while (tokens.Peek() == "case")
			{
				tokens.PopExpected("case");
				Expression value = Expression.Parse(tokens);
				tokens.PopExpected(":");
				Executable[] caseCode = CodeBlock.ParseSwitchCase(tokens);
				cases.Add(new SwitchCase(value, caseCode));
			}

			if (tokens.PopIfPresent("default"))
			{
				tokens.PopExpected(":");
				Executable[] defaultCode = CodeBlock.ParseSwitchCase(tokens);
				cases.Add(new SwitchCase(null, defaultCode));
			}

			tokens.PopExpected("}");

			return new Switch(condition, cases.ToArray());
		}

		public override void ResolveCode(Class c, Dictionary<object, object> parents)
		{
			this.Condition.ResolveCode(c, parents);
			foreach (SwitchCase switchCase in this.Cases)
			{
				switchCase.ResolveCode(c, parents);
			}
		}

		public override void ResolveClassToThis(Class c)
		{
			this.Condition.ResolveClassToThis(c);
			foreach (SwitchCase switchCase in this.Cases)
			{
				switchCase.ResolveClassToThis(c);
			}
		}
	}
}
